System and method for performing error recovery in an integrated development environment

ABSTRACT

A system and method for compiler error recovery, comprising analyzing the syntactic structure of a first program in a first programming language, wherein the first program can be represented by a first set of tokens, detecting a syntax error in the first program, remedying the syntax error by adding at least one token to the first set of tokens according to one of: 1) a prefix definition; and 2) an idiom definition, and wherein the detection of the syntax error occurs at the behest of an extensible compiler framework.

CLAIM OF PRIORITY

This application is a continuation of U.S. patent application Ser. No.10/678,344 entitled SYSTEM AND METHOD FOR PERFORMING ERROR RECOVERY INAN INTEGRATED DEVELOPMENT ENVIRONMENT, inventors Kevin Zatloukal, etal., filed Oct. 3, 2003, which claims priority to U.S. ProvisionalApplication No. 60/488,330, entitled SYSTEM AND METHOD FOR PERFORMINGERROR RECOVERY IN AN INTEGRATED DEVELOPMENT ENVIRONMENT, inventors KevinZatloukal, et al., filed Jul. 18, 2003, which are hereby incorporated byreference in their entirety.

COPYRIGHT NOTICE

A portion of the disclosure of this patent document contains materialwhich is subject to copyright protection. The copyright owner has noobjection to the facsimile reproduction by anyone of the patent documentor the patent disclosure, as it appears in the Patent and TrademarkOffice patent file or records, but otherwise reserves all copyrightrights whatsoever.

CROSS-REFERENCE TO RELATED APPLICATION

This application is related to the following co-pending applicationwhich is hereby incorporated by reference in its entirety:

U.S. patent application Ser. No. 10/678,248, entitled SYSTEM AND METHODFOR PERFORMING CODE COMPLETION IN AN INTEGRATED DEVELOPMENT ENVIRONMENT,inventors Kevin Zatloukal, et al., filed Oct. 3, 2003.

FIELD OF THE DISCLOSURE

The present invention disclosure relates to compiler design, and inparticular, error recovery and code completion.

BACKGROUND

Some integrated software development environments (IDEs) provide afeature referred to as code completion. Generally speaking, codecompletion is a facility that aids software developers by offeringsuggestions and/or information applicable to the completion ofexpressions or statements in a given programming language or paradigm.For example, in the Java™ programming language after a programmer entersan identifier name followed by a dot (‘.’) in a source code editor, codecompletion could present the programmer with a list of all possiblevalid names that could follow the dot. This saves the programmer theinconvenience of having to refer to the one or more source code files todetermine the correct information. Another example of code completioninvolves function or method calls. When a programmer types afunction/method name in a source code editor, the programmer can bepresented with a template of arguments for the function/method, and ifthere is more than one function/method with the given name, theprogrammer could be presented with a list of such templates to chosefrom. When there is only one possible way to complete a given languagestatement/expression, code completion can simply inscribe the requisitecode directly into the source code editor.

Typically, IDEs are implemented using two parsers. One parser is engagedto determine types and methods. A second parser is invoked when codecompletion is required. The second parser gathers information, typicallyin the form of a parse tree, by which a code completion facility candetermine possible completions of a given expression/statement. Thisarrangement is inherently inefficient, however, since two parsers arerequired by an IDE supporting this feature and since a given range ofsource code will be parsed more than once. An additional considerationin implementing a code completion system is the robustness of errorrecovery. In an IDE source code editor, statements/expressions are oftenin an incomplete and improper (from a language definition standpoint)grammatical state. Since code completion depends heavily on informationgenerated by a parser, parsers that do not recover well from errors willhamper this functionality.

BRIEF DESCRIPTION OF THE DRAWINGS

FIG. 1 is an illustration of a compiler framework for interactivesoftware development in an embodiment.

FIG. 2 is an illustration of a language module in accordance to oneembodiment.

FIG. 3 is an illustration of a parser with improved error recovery inaccordance to one embodiment.

FIG. 4 is an illustration of parser error recovery in accordance to anembodiment.

FIG. 5 is an illustration of prefix error recovery in one embodiment.

FIG. 6 is an illustration of idiom error recovery in one embodiment.

FIG. 7 is an illustration of code completion in one embodiment.

DETAILED DESCRIPTION

The invention is illustrated by way of example and not by way oflimitation in the figures of the accompanying drawings in which likereferences indicate similar elements. It should be noted that referencesto “an” or “one” embodiment in this disclosure are not necessarily tothe same embodiment, and such references mean at least one.

FIG. 1 is an illustration of a compiler framework for interactivesoftware development in an embodiment. Although this diagram depictscomponents as functionally separate, such depiction is merely forillustrative purposes. It will be apparent to those skilled in the artthat the components portrayed in this figure can be arbitrarily combinedor divided into separate software, firmware and/or hardware components.Furthermore, it will also be apparent to those skilled in the art thatsuch components, regardless of how they are combined or divided, canexecute on the same computing device or multiple computing devices, andwherein the multiple computing devices can be connected by one or morenetworks.

Referring to FIG. 1, a language-neutral, extensible compiler framework100 can provide compilation and related services to one or more clients108. By way of a non-limiting example, a client can be an IDE, othercompiler framework, and/or other suitable program/tool. Clients caninteract with the framework through client interface 112. One or morelanguage modules 106 can implement language-specific features, such asparsing, compilation and code generation for a given language (e.g.,Java™, C#, eXtensible Markup Language, etc.). Language modules caninteract with and provide services to the framework through languageinterface 110. Since the framework accommodates multiple languagemodules, clients can utilize it for projects containing more than oneprogramming language. In one embodiment, a client can cause theframework to request the services of one or more language modules byinforming the framework of changes to source code (e.g., as a result ofediting), among other things. Upon receiving such notification, theframework determines what source code files are affected by the changesand in what order to recompile them such that any dependencies aresatisfied. Tasks to perform recompilation are managed by task manager102. Recompilation tasks can be multithreaded and can invoke theservices of the language module(s) through the language interface. Theframework can also provide clients with code completion services througha code completion module 114. The client and language interfaces can beimplemented in a number of ways including, but not limited to, asapplication program interfaces, service provider interfaces, sharedmemory, communication protocols, distributed objects, data structures,and other suitable means without departing from the spirit and scope ofthe present disclosure.

FIG. 2 is an illustration of a language module in accordance to oneembodiment. Language modules can provide language-specificfunctionality, such as parsing, semantic checking, name resolution andcode generation to the framework 100. The framework includes ascanner/parser component 200 which can provide scanning/parsing servicesto the framework. The scanner/parser component can operate in anincremental fashion, a batch fashion or some combination thereof. Ascanner generally splits expressions and language statements into tokenswhich can then be processed by a parser in order to discover thegrammatical structure of a program. In doing so, the parser can generatea parse tree or other representation of the program. The presentdisclosure is not limited to textual programming languages. In oneembodiment, a programming language can be graphical in nature (e.g., aprogram can be represented by graphical depictions and associationsthere between). As will be apparent to one of skill in the art, suchgraphical depictions and associations can be mapped into a linearprogramming language which can then be processed by the scanner/parsercomponent.

The framework includes a name space component 104 which can be used bylanguage components to store symbols (e.g., identifiers, types), and toperform name resolution 204 and dependency checking. In one embodimentlanguage modules can utilize the symbol information of other languagemodules (e.g., when multiple languages interact). In addition, thesymbol information in a parse tree can refer to corresponding entries inthe name space. The semantic checker component 202 can perform semanticchecking of the program. Semantic checking can catch errors that are notdiscernable from the syntactic structure of a program. Code generator206 can translate a representation of the language parsed by thescanner/parser to a target language. By way of a non-limiting example,the target language can be low-level (e.g., machine code), intermediate(e.g., Java byte code), or high-level (e.g., another programminglanguage). In one embodiment, the target language for all languagemodules is the same.

FIG. 3 is an illustration of a parser with improved error recovery inaccordance to one embodiment. Although this diagram depicts componentsas functionally separate, such depiction is merely for illustrativepurposes. It will be apparent to those skilled in the art that thecomponents portrayed in this figure can be arbitrarily combined ordivided into separate software, firmware or hardware components.Furthermore, it will also be apparent to those skilled in the art thatsuch components, regardless of how they are combined or divided, canexecute on the same computing device, multiple computing devices, or canbe arbitrarily distributed among different computing devices connectedby one or more networks.

Referring to FIG. 3, parser 306 consumes tokens from the token stream312 and generates parse tree 300. In this endeavor, the parser utilizeslanguage grammar 304 (e.g., an LALR(1), LL(1), etc.) which provides thesyntax rules for properly formed language statements. The parser canoperate in an incremental fashion, a batch fashion or some combinationthereof. By way of a non-limiting example, the parser can betable-driven such that successive grammar states are encoded into amatrix that drives token consumption. Other parser implementations arepossible and well known in the art. The present invention is not limitedto or dependent on a particular parser implementation. Parse stack 302is used by the parser to keep track of where in the grammar a particularsequence of input tokens has led it. In one embodiment, the top of thestack represents the current parse state and states preceding it are onthe stack in order of most recent (closest to the top of the stack) toleast recent.

In one embodiment, when the parser detects a syntax error it can invokea number of error recovery mechanisms. Two possible error recoverymechanisms are embodied in prefix component 314 and idiom component 310,respectively. These components will be discussed in detail below. Bothcomponents attempt to “fix” an invalid or incomplete language statementby introducing new tokens into the token stream and/or by altering theparse stack so that the parser can continue past the error. The prefixcomponent tries to introduce prefix/terminator combinations whereas theidiom component attempts to introduce specific token sequences that fixcommonly occurring errors in a given language.

In one embodiment, the idiom and prefix components can make use of alook-ahead parser 318 which in turn can make use of a look-ahead tokenbuffer 320 and a look-ahead stack 322. The look-ahead token buffer andlook-ahead stack can be used by the look-ahead parser to perform trialparses on “fixes” introduced by error recovery mechanisms to determineif the parser can get beyond a given syntax error. If an error isremedied, any new information in the look-ahead stack and look-aheadtoken buffer can be transferred to the stack and token stream,respectively. This will allow the parser to pick up where it left offand get beyond the syntax error. In one embodiment, the number of tokensin the look-ahead buffer is equal to the number of tokens introduced byan error recovery mechanism plus a minimum number of tokens that theparser is required to consume in order to be considered free and clearof the error condition. In one embodiment, the minimum number of tokensis three. In one embodiment, the parser and the look-ahead parser arethe same.

FIG. 4 is an illustration of parser error recovery in accordance to anembodiment. Although this figure depicts functional steps in aparticular order for purposes of illustration, the process is notlimited to any particular order or arrangement of steps. One skilled inthe art will appreciate that the various steps portrayed in this figurecould be omitted, rearranged, combined and/or adapted in various ways.

In Step 400, attempts can be made to modify the token stream and/orstack of the parser to fix a syntax error. In one embodiment, a closingdelimiter followed by a terminator can be introduced. The parser stackand the token stream can be examined for unmatched delimiter tokens. Forexample, if the opening delimiter characters ‘(’, ‘{’, and ‘[’ werefound, then one would expect to find matching closing delimitercharacters ‘)’, ‘}’, and ‘]’. In the case of a missing closingdelimiter, however, an appropriate closing delimiter token can beinserted onto the stack or into the token stream to fix the problem. Thecombination of an opening delimiter with an newly created closingdelimiter is termed a prefix.

A language module can specify tokens that serve as opening and closingdelimiters. A language module can also define special case rules. In oneembodiment, and by way of a non-limiting example, there can be a rulefor the Java language pertaining to the dot (‘.’) token. If the dottoken is at the top of the stack, then it is considered an openingdelimiter. The appropriate closing delimiter in this case is anidentifier immediately following the dot. If such a closing delimiter isnot found, error recovery can insert a dummy identifier token into thetoken stream.

Once a prefix has been established, error recovery attempts to pair itwith a terminator token. In one embodiment, the terminator chosendepends on the prefix. By way of a non-limiting example, if a prefixends with a closing delimiter of ‘)’, then in the Java language asemicolon is a possible appropriate terminator since the ‘)’ could bethe end of a statement. By way of a second non-limiting Java example, ifthere is an empty prefix, error recovery can introduce a ‘+’ token. Thatway if a user had typed “foo bar” (which is not legal in Java), the ‘+’in between “foo” and “bar” will create a syntactically valid expression.In yet another embodiment, a terminator can be empty. By way of anothernon-limiting Java example, error recovery can attempt to pair the prefixwith a semicolon.

Still referring to Step 400, in another embodiment language-specificidioms can be introduced into the token stream and/or stack of theparser to fix a syntax error. An idiom is a specific insertion sequencethat can be used to overcome common errors in a given programminglanguage. By way of a non-limiting example, Table 1 lists several idiomsthat can be used in conjunction with common syntax errors in the Javalanguage. In Table 1, “<id>” refers to a new dummy identifier.

TABLE 1 Java Idioms in one Embodiment JAVA SYNTAX ERROR INSERTED IDIOMmissing identifier <id> ; malformed method call <id> ) ; malformedmethod call <id> ) ; } malformed declaration <id> ; } class body missing<id> { } “catch” missing <id> ; } finally { } “catch” missing finally {} “catch” missing finally { } } declarations outside class body class<id> {

In Step 402, a determination can be made as to whether error correctionhas enabled to the parser to continue past the syntax error. If so, thestack and/or token stream are modified in Step 404 to introduce the fix.If not, states can be popped off of the parse stack until an errorproduction is removed. In one embodiment, an error production is definedby the grammar. By way of a non-limiting example pertaining to thegrammar language in YACC (Yet Another Compiler Compiler), an errorproduction (or rule) can be defined as follows:

stmt ::= expr SEMI | while_stmt SEMI | if_stmt SEMI | error SEMI

This grammar rule for a language statement (“stmt”) indicates that if aparse error (“error”) is encountered during parsing one of the statementrules (i.e., “expr SEMI”, “while_stmt SEMI” and “if stmt SEMI”), theparser can get beyond it (and potentially recover) once a semicolon(“SEMI”) token has been consumed. By way of a non-limiting example,tokens could be popped off of the stack until the “error” token isencountered. Then, excess tokens in the token stream could beconsumed/discarded until parsing succeeds (Step 408).

In another embodiment, an additional error recovery technique that canbe employed is to incorporate illegal language constructions into thegrammar itself. This can be done assuming that the illegal grammar rulesdo not cause the grammar to become ambiguous.

FIG. 5 is an illustration of prefix error recovery in one embodiment.Although this figure depicts functional steps in a particular order forpurposes of illustration, the process is not limited to any particularorder or arrangement of steps. One skilled in the art will appreciatethat the various steps portrayed in this figure could be omitted,rearranged, combined and/or adapted in various ways.

Referring to FIGS. 3 and 5, in Step 500 a determination is made as towhether there are any more prefixes available to apply to the givensyntax error. If not, a token is deleted from the look-ahead tokenbuffer in Step 504. A determination is then made in Step 506 as towhether there are any more tokens left in the look-ahead token buffer.If no more tokens remain, prefix error recovery fails. Assuming thereare more prefixes to try, a prefix is selected in Step 502. In Step 508,a determination is made as to whether there are any remainingterminators to pair with the selected prefix. If not, processingcontinues at Step 500. If there is another terminator to pair with theselected prefix, the terminator is selected in Step 510. In Step 512,the selected prefix/terminator pair is introduced into the look-headtoken buffer and/or look-ahead stack. In Step 514, a determination ismade as to whether the look-ahead parser was able to successfully parsewith the fix in place. If so, error recovery succeeds. Otherwise,processing continues at Step 508 where another terminator will bepotentially paired with the selected prefix.

FIG. 6 is an illustration of idiom error recovery in one embodiment.Although this figure depicts functional steps in a particular order forpurposes of illustration, the process is not limited to any particularorder or arrangement of steps. One skilled in the art will appreciatethat the various steps portrayed in this figure could be omitted,rearranged, combined and/or adapted in various ways.

Referring to FIGS. 3 and 6, in Step 600 a determination is made as towhether there are any remaining idioms left to apply to a given syntaxerror. If not, a token is deleted from the look-ahead token buffer inStep 602. A determination is then made in Step 608 as to whether thereare any more tokens left in the look-ahead token buffer. If no moretokens remain, idiom error recovery fails. Assuming there are moreidioms to try, an idiom is selected in Step 604. In Step 610, theselected idiom is introduced into the look-head token buffer and/orlook-ahead stack. In Step 612, a determination is made as to whether thelook-ahead parser was able to successfully parse with the fix in place.If so, error recovery succeeds. Otherwise, processing continues at Step600 where another idiom will potentially be selected.

Robust parser error recovery as described above directly benefits codecompletion. Code completion is a facility that aids software developersby offering suggestions and/or information applicable to the completionof expressions or statements in a given programming language orparadigm. For example, in the Java™ programming language after aprogrammer enters an identifier name followed by a dot (‘.’) in a sourcecode editor, code completion could present the programmer with a list ofall possible valid names that could follow the dot. This saves theprogrammer the inconvenience of having to refer to the one or moresource code files to determine the correct information to complete thestatement/expression. Another example of code completion involvesfunction or method calls. When a programmer types a function/method namein a source code editor, the programmer can be presented with a templateof arguments for the function/method, and if there is more than onefunction/method with the given name, the programmer could be presentedwith a list of such templates to chose from. When there is only onepossible way to complete a given language statement/expression, codecompletion can simply inscribe the requisite code directly into thesource code editor.

In one embodiment and by way of a non-limiting example, the frameworkcan make available code completion services to clients through theclient interface. In one embodiment, such an interface can includemethods as listed in Table 2. The methods can include as arguments alocation in a source code file/program at or near which code completioncan be applied. In one embodiment, the location can be an textual offset(e.g., a character count) into a program. Textual offsets are merely onetechnique for indicating a location within a program. As is apparent tothose of skill in the art, a location may also be specified bystructural navigation through a parse tree, via indication of semanticentities within the program, through a token or token range within thelexical stream, and so forth. The framework can map the method to alanguage model associated with the source code at the specifiedlocation. The language module can provide some or all of the informationrequested by the method to the framework. The framework can then providethis information to the client that requested it.

The program location provided to the method can be mapped to a locationin a language module's parse tree. The location in the parse tree willpotentially refer to a complete or incomplete name of some kind (e.g., apackage or library name, a class name, a method name, a field name, avariable name). The language module can use information in the parsetree in conjunction with information in the name space to generate alist of possible code completions. This information can then beinteractively presented to an end-user by a client.

TABLE 2 Code Completion Services in one Embodiment CODE COMPLETIONMETHOD DESCRIPTION getCompletionRange(location) Returns to a client therange in a programprogram that holds the current value of the completionthat has been chosen by an end-user or the client.getCompletions(location) Returns all of the possible objects (e.g.,classes, methods, fields, functions, variables, etc.) whose names couldbe used in place of the identifier at the given location in theprogramprogram (or that would be at the given location).getEnclosingConprogram Returns information about the (location)enclosing conprograms of the given program location. By way of a non-limiting example, this method could return the name of enclosing method,function or class definitions. getIdentifierInfo(location) Returns namespace information pertaining to the identifier at the given programlocation. getRange(location, symbol) Returns the start location of thegiven symbol, which was returned from querying about the given location.isCompletionChar(location, Determines whether the given character)character, just typed, should initiate an attempt at completion (after apause).

Clients can provide code completion services to end-users in a number aways, including but not limited to, via pop-up windows/menus, statusdisplays, key and/or mouse click sequences, sounds and other suitablemeans. By way of a non-limiting example, a client could present the userwith a pop-up window containing a list of possible code completions. Asthe user enters more text, the list could shrink to include only thosecompletions that are still valid in light of the newly entered text. Ifa client allows an end-user to select a given code completion, theclient can automatically insert this information into the source code,thus completing the code.

FIG. 7 is an illustration of code completion in one embodiment. Althoughthis figure depicts functional steps in a particular order for purposesof illustration, the process is not limited to any particular order orarrangement of steps. One skilled in the art will appreciate that thevarious steps portrayed in this figure could be omitted, rearranged,combined and/or adapted in various ways. In Step 700, a language modulefinds the nearest expression to the specified program location in itsparse tree. In Step 702, the language module and/or framework obtainscode completion information relevant to the expression from the parsetree itself and/or the name space. In Step 704, the code completioninformation can be provided to a client.

One embodiment may be implemented using a conventional general purposeor a specialized digital computer or microprocessor(s) programmedaccording to the teachings of the present disclosure, as will beapparent to those skilled in the computer art. Appropriate softwarecoding can readily be prepared by skilled programmers based on theteachings of the present disclosure, as will be apparent to thoseskilled in the software art. The invention may also be implemented bythe preparation of integrated circuits or by interconnecting anappropriate network of conventional component circuits, as will bereadily apparent to those skilled in the art.

One embodiment includes a computer program product which is a storagemedium (media) having instructions stored thereon/in which can be usedto program a computer to perform any of the features presented herein.The storage medium can include, but is not limited to, any type of diskincluding floppy disks, optical discs, DVD, CD-ROMs, microdrive, andmagneto-optical disks, ROMs, RAMs, EPROMs, EEPROMs, DRAMs, VRAMs, flashmemory devices, magnetic or optical cards, nanosystems (includingmolecular memory ICs), or any type of media or device suitable forstoring instructions and/or data.

Stored on any one of the computer readable medium (media), the presentinvention includes software for controlling both the hardware of thegeneral purpose/specialized computer or microprocessor, and for enablingthe computer or microprocessor to interact with a human user or othermechanism utilizing the results of the present invention. Such softwaremay include, but is not limited to, device drivers, operating systems,execution environments/containers, and applications.

The foregoing description of the preferred embodiments of the presentinvention has been provided for the purposes of illustration anddescription. It is not intended to be exhaustive or to limit theinvention to the precise forms disclosed. Many modifications andvariations will be apparent to the practitioner skilled in the art.Embodiments were chosen and described in order to best describe theprinciples of the invention and its practical application, therebyenabling others skilled in the art to understand the invention, thevarious embodiments and with various modifications that are suited tothe particular use contemplated. It is intended that the scope of theinvention be defined by the following claims and their equivalents.

1. A system for code completion compiler error recovery while creatingsoftware code in an integrated development environment, comprising: aprocessor; means for parsing the syntactic structure of a first programin a first programming language, implemented on the processor, whereinthe first program can be represented by a first set of tokens; means fordetecting a syntax error in the first program, implemented on theprocessor; means for correcting the syntax error by adding at least onetoken to the first set of tokens, implemented on the processor,according to one of: 1) a prefix, wherein a prefix is the combination ofan opening delimiter with a newly created closing delimiter; and 2) anidiom, wherein an idiom is a specific insertion sequence that can beused to overcome common errors in a given programming language; andwherein an extensible compiler framework detects the syntax error.
 2. Anintegrated development environment code completion compiler errorrecovery system, comprising: a processor; a language module, implementedon the processor, including a parser operable to parse the syntacticstructure of a first program in a first programming language, whereinthe first program can be represented by a first set of tokens; a clientinterface through which the language module can communicate with anextensible compiler framework, implemented on the processor; theextensible compiler framework including a namespace component whereinthe namespace component is operable to store name and/or typeinformation for one or more language modules; and wherein the parser cancorrect a syntax error by adding at least one token to the first set oftokens according to one of: 1) a prefix, wherein a prefix is thecombination of an opening delimiter with a newly created closingdelimiter; and 2) an idiom, wherein an idiom is a specific insertionsequence that can be used to overcome common errors in a givenprogramming language; and wherein an extensible compiler frameworkdetects the syntax error.
 3. The system of claim 2 wherein: the syntaxerror can be corrected by removing at least one token from the first setof tokens according to a grammar rule if the syntax error cannot beremedied by adding at least one token to the set of tokens.
 4. Thesystem of claim 3 wherein: the grammar rule incorporates the syntaxerror into a grammatical of the first programming language.
 5. Thesystem of claim 2 wherein: the prefix includes an opening delimiter anda closing delimiter.
 6. The system of claim 2 wherein: the prefixassociates an unmatched delimiter with the at least one token.
 7. Thesystem of claim 2 wherein: the at least one token is an operator ifthere is no applicable prefix.
 8. The system of claim 2 wherein: theidiom associates a syntax error with the at least one token.
 9. Thesystem of claim 2 wherein the step of remedying the syntax errorincludes: adding a terminator to the first set of tokens.
 10. The systemof claim 2 wherein: the extensible compiler framework can integrate andinteract with compilers for different programming languages through acommon interface.
 11. The system of claim 2 wherein: the first programin the first programming language can be nested within a second programin a second programming language.
 12. The system of claim 2 wherein: asecond program in a second programming language is nested within thefirst program in the first programming language.